package com.arsn.myf.common.util.auth;

import com.arsn.myf.common.util.http.ServletUtils;
import com.arsn.myf.security.entity.UserInfo;
import com.arsn.myf.security.service.TokenService;
import com.arsn.myf.system.entity.Dept;
import com.arsn.myf.system.entity.User;
import liquibase.pro.packaged.B;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 权限工具类
 * @author zhongrj
 * @since 2022-11-10
 */
@Component
public class AuthUtil {

    private static AuthUtil authUtil;

    @Autowired
    private TokenService tokenService;

    @PostConstruct
    public void init(){
        authUtil = this;
        authUtil.tokenService = this.tokenService;
    }


    /**
     * 获取用户名
     * @return
     */
    public static String getUsername(){
        UserInfo user = getUser();
        // 获取token并返回
        return null==user?null:user.getUsername();
    }

    /**
     * 获取用户角色
     * @return
     */
    public static String getUserRole(){
        UserInfo user = getUser();
        // 获取token并返回
        return null==user?null:getUserRole(user);
    }

    /**
     * 获取用户角色
     * @param userInfo
     * @return
     */
    public static String getUserRole(UserInfo userInfo){
        List<String> list = new ArrayList<>();
        Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();
        authorities.forEach(grantedAuthority -> {
            list.add(grantedAuthority.getAuthority().split("_")[1]);
        });
        return String.join(",",list);
    }

    /**
     * 获取用户ID
     * @return
     */
    public static Long getUserId(){
        UserInfo user = getUser();
        // 获取token并返回
        return null==user?null:user.getId();
    }

    /**
     * 获取用户信息
     * @return
     */
    public static UserInfo getUser(){
        // 获取 servletRequest
        HttpServletRequest request = ServletUtils.getRequest();
        // 获取token并返回
        return authUtil.tokenService.getLoginUser(request);
    }
}
